package com.cxf.windex.service.impl;

import com.cxf.windex.base.util.MapUtil;
import com.cxf.windex.base.util.XiaoBaoUtil;
import com.cxf.windex.biz.JsUserBiz;
import com.cxf.windex.entity.JsUser;
import com.cxf.windex.service.ProcPlanService;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenxf
 * @date 4/17/2018
 * @description
 */
@Service
public class UserServiceImpl implements ProcPlanService {
  @Autowired
  private JsUserBiz jsUserBiz;

  @Value("${weixin.appid}")
  private String appid;

  @Value("${xiaobao.uri}")
  private String uri;

  @Value("${xiaobao.userApi}")
  private String userApi;

  public static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
  /**
   * 循环处理机器人算力 直到false
   * @return
   */
  @Override
  public boolean procPlan() {
    Example example = new Example(JsUser.class);
    Criteria criteria = example.createCriteria();
    criteria.andEqualTo("status","0");
    PageHelper.startPage(1, 1);
    List<JsUser> items = jsUserBiz.selectByExample(example);
    if(items.size()==0){
        return false;
    }
    JsUser jsUser=items.get(0);
    jsUser.setStatus("1");
    Map paramMap=new HashMap<String,Object>();
    try {
      paramMap.putAll( MapUtil.objectToMap(jsUser));
      paramMap.put("token",appid);
      paramMap.put("userid",jsUser.getId());
      paramMap.put("addtime",jsUser.getCrtTime());
      paramMap.remove("id");
      paramMap.remove("crtTime");
      paramMap= XiaoBaoUtil.saveApi(paramMap,uri,userApi);
      if(paramMap.get("code").equals("0")){
        //更新状态
        jsUserBiz.updateSelectiveById(jsUser);
      }else{
        //同步异常
        jsUser.setStatus("4");
        jsUserBiz.updateSelectiveById(jsUser);
      }
      logger.debug("map={}",paramMap);
    } catch (Exception e) {
      e.printStackTrace();
      jsUser.setStatus("4");
      jsUserBiz.updateSelectiveById(jsUser);
    }

    return true;
  }
}
